|
vs 2013 express for web
I have an MVC 4 web app and a WebAPI service returning JSON formatted data.
I tried to use Ajax.BeginForm to call the WebAPI service.
It does call it correctly
@model IEnumerable<MyApp.Models.SomeClass>
@using (Ajax.BeginForm(
new AjaxOptions
{
HttpMethod = "get",
Url="api/MyWebAPI",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Resultlist"
}))
{
<div class="row">
<div class="col-lg-12">
<h3>Service Call Details - Method A</h3>
<input type="submit" class="btn btn-default" value=" Get Via Asynch Method A " />
</div>
</div>
}
<div id="ResultList">
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Caption)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>
@Html.DisplayNameFor(model => model.Active)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Caption)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ClassifierGroupId }) |
@Html.ActionLink("Details", "Details", new { id = item.ClassifierGroupId }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ClassifierGroupId })
</td>
</tr>
}
</table>
</div>
But the results don't fill the form.
Now, when the data came from the Home controller's Index function, that returned data as a View with model as an ActionRequest...:
public ActionResult Index()
{
ViewBag.Title = "Home Page";
IEnumerable<SomeClass> model = db.SomeClasses.ToList();
return View(model);
}
So how do I convert the WepAPI returned JSON data to something that the razor form can use for the Model data?
Any help appreciated.
GS
GaltSalt
maker of .Net thingys
|
|
|
|
|
The service is doing exactly what it's supposed to: return data.
What I really need is to convert that data into the PartialView that it belongs in.
I'm guessing there's no real way to do this in JavaScript, is there?
The only thing you can do is build the HTML manually in JavaScript.
So calling a WebAPI in Asynch JS is basically a useless oddity if what you want to do is send the contents to a View or PartialView, like it would from calling your Index controller function.
Can anyone prove otherwise?
maker of .Net thingys
|
|
|
|
|
I used another asych request to call the controller with the data - but this is only useful if the WebAPI service is on a different server.
maker of .Net thingys
|
|
|
|
|
Dear All,
I have no experience to build API before at all.
I'm using ASP.NET Web Form with C#.
How to start?
Thanks,
|
|
|
|
|
This isn't a good question for here. Try Google search for tutorial.
Even Microsoft.
http://www.asp.net/mvc/tutorials
GaltSalt
maker of .Net thingys
|
|
|
|
|
|
I need source code for sending sms using asp.net C# through gsm modem or Boardband of any brand please any one help
|
|
|
|
|
Don't Repost[^]
This question has been answered so many times
Check this[^]
To learn all there is to know. I know I'll be disappointed one day, but I've made a good start, and the eventual disappointment is likely to be brief.
-Roger Wright
|
|
|
|
|
Here we answer specific questions which members face during programming.
We can't work on the whole source code. You need to do that yourself.
If you face any difficulty while coding, feel free to come back here and ask another question with specific issue describing the scenario.
Members will be happy to help you then.
|
|
|
|
|
Hi All,
Its killing my time I have been freaking with it, for some time I was a using a computer in which I didn't have this problem. Now my company gave me new computer I started getting this problem. Since two days I am just dieing to run my application. Without running my application what can I do? I just don't want any encryption and decryption on my machine, if they want to do it on the Server let them do it. If I want to say I don't want to play with any encryption or decryption where can I say that. Why the heck isn't simple to say that I don't want it. I have been researching, but every one is explaining how to encrypt or decrypt but no one is saying how just get out of it. I don't want it that's it.
I have an asp.net application, I don't want to encrypt or decrypt my web config file, but still I am getting the following error. How can I say that I want neither encryption nor decryption for my application on my machine.
I went into Machine.Config file and commented the RSA Encryption section as below
<!--<configProtectedData defaultProvider="RsaProtectedConfigurationProvider">
<providers>
<add name="RsaProtectedConfigurationProvider" type="System.Configuration.RsaProtectedConfigurationProvider,System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" description="Uses RsaCryptoServiceProvider to encrypt and decrypt" keyContainerName="NetFrameworkConfigurationKey" cspProviderName="" useMachineContainer="true" useOAEP="false"/>
<add name="DataProtectionConfigurationProvider" type="System.Configuration.DpapiProtectedConfigurationProvider,System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" description="Uses CryptProtectData and CryptUnProtectData Windows APIs to encrypt and decrypt" useMachineProtection="true" keyEntropy=""/>
</providers>
</configProtectedData>-->
And my Web config doesn't have any encrypt or decrypt functionality defined as below.
<add key="SqlServerConnectionString" value="data source=xxxxSQLTEST\Prod;initial catalog=xxxx;password=xxxxxxxxxxx;persist security info=True;user id=xxxxxx"/>
<add key="OracleConnectionString" value="data source=xxxx;password=incnpdev;user id=xxxxx"/>
<add key="OleDbConnectionString" value="data source=(local);initial catalog=xxxxxx;password=xxxxxx;persist security info=True;user id=xxxxx"/>
Here is the following Error I am getting.
Server Error in '/apps/cnpweb/zzfdpsource/ORFdpProd' Application.
--------------------------------------------------------------------------------
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred loading a configuration file: The protection provider 'RsaProtectedConfigurationProvider' was not found.
Source Error:
[No relevant source lines]
Source File: C:\inetpub\localinternet\webcon.config Line: 0
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18067
But if I keep the RSA section in the machine config file I am getting the following error. Why MS creates things like this. I don't even understand what is wrong. I the old machine I was not having this error, but when I got new machine to work on I am getting the following error. The same settings are there on every other developers machine they are not getting any error. This is making me nervous. Is my machine is incorrect what is wrong?
Server Error in '/apps/cnpweb/zzfdpsource/ORFdpProd' Application.
--------------------------------------------------------------------------------
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: Bad Data.
Source Error:
Line 2: <!-- External Connection Strings from Microsoft: http:
Line 3: <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
Line 4: <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
Line 5: xmlns="http://www.w3.org/2001/04/xmlenc#">
Line 6: <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
Source File: C:\inetpub\localinternet\webcon.config Line: 4
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18067
When I am trying other thing I am getting the following error.
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC>aspnet_regiis -pa "NetFrameworkConfigurationKey" "ASPNET"
Microsoft (R) ASP.NET RegIIS version 4.0.30319.17929
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Adding ACL for access to the RSA Key container...
No mapping between account names and security IDs was done. (Exception from HRESULT: 0x80070534)
Failed!
With all these error messages if someone can give me any idea or link or any sort of help. I will be very very thankful. I don't know what to do? I am researching heavily but no clue till now. Please help me, thanks in advance.
Thanks & Regards,
Abdul Aleem Mohammad
St Louis MO - USA
modified 14-Feb-14 19:30pm.
|
|
|
|
|
I want to select multiple rows of gridview using shift+select functionality. My condition is that there are no checkboxes. The user has to select the user on clicking the row and that row's color should change accordingly. Can anyone help? I am looking for this functionality from a long time. I have been able to get this functionality using checkboxes but that is not what i want.reply me pls.
|
|
|
|
|
|
plz tell me any one , The name of the free sms sending gateways for sending sms from different free sms web site
modified 14-Feb-14 10:24am.
|
|
|
|
|
Here you go: Free SMS[^]
The difficult we do right away...
...the impossible takes slightly longer.
|
|
|
|
|
|
As a part of my website, I need to diaplay a .swf file in my home page. Could anyone please tell me how to insert the .swf file in ASP.Net page
|
|
|
|
|
|
<div class="WelcomeImage">
<object type="application/x-shockwave-flash" data="~/Images/slideshow_header02.swf"
width="200" height="100">
<param name="movie" value="~/Images/slideshow_header02.swf" />
</object>
</div>
This is my code which is not displaying anything..should i need to do anything else..
|
|
|
|
|
Make sure you have referred right swf file(path & file name).
Make sure you have swf files in that path.
Load some other swf file & make sure it's loading. If it's loading then the problem in your swf.
thatrajaCode converters | Education Needed
No thanks, I am all stocked up. - Luc Pattyn
When you're wrestling a gorilla, you don't stop when you're tired, you stop when the gorilla is - Henry Minute
|
|
|
|
|
Hi,
I am trying to get the following code read credentials from the user class but I experiencing the following principal error -- "The name 'PrincipalProvider' does not exist in the current context".
public class BasicAuthMessageHandler : DelegatingHandler
{
bool _RequireSsl = true;
public bool RequireSsl
{
get { return _RequireSsl; }
set { _RequireSsl = value; }
}
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
[Inject]
public iUser Repository { get; set; }
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
{
api_login parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
{
Thread.CurrentPrincipal = PrincipalProvider
.CreatePrincipal(parsedCredentials.username, parsedCredentials.password);
}
}
return base.SendAsync(request, cancellationToken)
.ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized
&& !response.Headers.Contains(BasicAuthResponseHeader))
{
response.Headers.Add(BasicAuthResponseHeader
, BasicAuthResponseHeaderValue);
}
return response;
});
}
private api_login ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert
.FromBase64String(authHeader))
.Split(
new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0])
|| string.IsNullOrEmpty(credentials[1])) return null;
return new api_login()
{
username = credentials[0],
password = credentials[1],
};
}
private bool Authenticate(HttpContextBase context)
{
if (_RequireSsl && !context.Request.IsSecureConnection && !context.Request.IsLocal) return false;
if (!context.Request.Headers.AllKeys.Contains("Authorization")) return false;
string authHeader = context.Request.Headers["Authorization"];
IPrincipal principal;
if (TryGetPrincipal(authHeader, out principal))
{
HttpContext.Current.User = principal;
return true;
}
return false;
}
private bool TryGetPrincipal(string authHeader, out IPrincipal principal)
{
var creds = ParseAuthHeader(authHeader);
if (creds != null)
{
if (TryGetPrincipal(creds[0], creds[1], out principal)) return true;
}
principal = null;
return false;
}
private string[] ParseAuthHeader(string authHeader)
{
if (authHeader == null || authHeader.Length == 0 || !authHeader.StartsWith("Basic")) return null;
string base64Credentials = authHeader.Substring(6);
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(base64Credentials)).Split(new char[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[0])) return null;
return credentials;
}
private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
{
api_login user = Repository.Validate2(userName, password);
if (user != null)
{
principal = new GenericPrincipal(new GenericIdentity(user.username));
return true;
}
else
{
principal = null;
return false;
}
}
User class methods:
public api_login GetData(string userName)
{
return db.api_login.FirstOrDefault(c => c.username == userName);
}
public api_login Validate2(string userName, string Password)
{
return db.api_login.FirstOrDefault(u => u.username == userName && u.password == Password);
}
Many thans for your help and time.
|
|
|
|
|
It looks like some of that code has come from this blog post[^], but you're missing the PrincipalProvider property, the IProvidePrincipal interface, and the implementation of that interface.
You've got quite a few methods which don't appear to be called. Your RequireSsl property is only used from the Authenticate method, which is never called.
Looking at the Validate2 method, it appears you're storing passwords in plain text, which is a very bad idea. You should be storing salted hashes of the password:
Salted Password Hashing - Doing it Right[^]
Removing the unused methods and property, it looks like you need to use your TryGetPrincipal method instead of PrincipalProvider.CreatePrincipal to get the IPrincipal for the request:
public class BasicAuthMessageHandler : DelegatingHandler
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
[Inject]
public iUser Repository { get; set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;
if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
{
api_login parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
if (parsedCredentials != null)
{
IPrincipal principal;
if (TryGetPrincipal(parsedCredentials.username, parsedCredentials.password, out principal))
{
Thread.CurrentPrincipal = principal;
}
}
}
return base.SendAsync(request, cancellationToken).ContinueWith(task =>
{
var response = task.Result;
if (response.StatusCode == HttpStatusCode.Unauthorized && !response.Headers.Contains(BasicAuthResponseHeader))
{
response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
}
return response;
});
}
private api_login ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1])) return null;
return new api_login()
{
username = credentials[0],
password = credentials[1],
};
}
private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
{
api_login user = Repository.Validate2(userName, password);
if (user != null)
{
principal = new GenericPrincipal(new GenericIdentity(user.username));
return true;
}
principal = null;
return false;
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you so much for clarifying the basicAuthHandler class for me. I really appreciate your help and time. I am working on the validate method ( from user class) on the side, to be able to encrypt the passwords (thank you for providing an framework for storing password).
I am currently stuck on the following logic below and would like to request some of your advice. I would like to be able to pass principal identity name only, not the role. Is this plausible? if not, how would i create role for a user. Would i need to call that within my user class method validate?
private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
{
api_login user = Repository.Validate2(userName, password);
if (user.username != null)
{
principal = new GenericPrincipal(new GenericIdentity(user.username));
return true;
}
principal = null;
return false;
}
}
Many thanks for your time and help.
|
|
|
|
|
If you don't want to specify any roles for the principal, just pass null to the roles parameter:
principal = new GenericPrincipal(new GenericIdentity(user.username), null);
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard,
Thank you so much for help with prior issue with the basic authentication. I am trying to add error messages/exceptions, if the user has either failed to Login or if user credentials are blank. In the code below, I am using throw new HttpResponseException(HttpStatusCode.Unauthorized); , and this currently not showing up for failing user log-ins. I am testing this on the built-in 'values' api controller class by using the '[authorize]' function on top of the values api controller class.
private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
{
api_login user = repository.Validate2(userName, password);
if (user.username != null)
{
principal = new GenericPrincipal(new GenericIdentity(user.username), null);
}
else if (user.username == null)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
principal = null;
return false;
}
This is what my BasicAuthHandler class currently looks like. I am not sure whether i would need to create and I am currently not getting anything on the client-side if user credentials are null or pressed cancel on the login dialog.
public class BasicAuthHandler : DelegatingHandler
{
private const string BasicAuthResponseHeader = "WWW-Authenticate";
private const string BasicAuthResponseHeaderValue = "Basic";
public BasicAuthHandler(iUser repository)
{
this.repository = repository;
}
[Inject]
iUser repository { get; set; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
AuthenticationHeaderValue authValue = request.Headers.Authorization;
if (authValue == null || authValue.Scheme != BasicAuthResponseHeaderValue)
{
return Unauthorized(request);
}
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authValue.Parameter)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
{
return Unauthorized(request);
}
api_login user = repository.Validate2(credentials[0], credentials[1]);
if (user == null)
{
return Unauthorized(request);
}
IPrincipal principal = new GenericPrincipal(new GenericIdentity(user.username, BasicAuthResponseHeaderValue), null);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return base.SendAsync(request, cancellationToken);
}
private Task<HttpResponseMessage> Unauthorized(HttpRequestMessage request)
{
var response = request.CreateResponse(HttpStatusCode.Unauthorized);
response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
var task = new TaskCompletionSource<HttpResponseMessage>();
task.SetResult(response);
return task.Task;
}
private api_login ParseAuthorizationHeader(string authHeader)
{
string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });
if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1])) return null;
return new api_login()
{
username = credentials[0],
password = credentials[1],
};
}
private bool TryGetPrincipal(string userName, string password, out IPrincipal principal)
{
api_login user = repository.Validate2(userName, password);
if (user.username != null)
{
principal = new GenericPrincipal(new GenericIdentity(user.username), null);
}
else if (user.username == null)
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
principal = null;
return false;
}
}
Many thanks for your time and help.
|
|
|
|
|
I'm not surprised the changes to the TryGetPrincipal method aren't having any effect - you're not calling it anywhere!
The Unauthorized method is sending back a 401 response with the WWW-Authenticate header, which looks like the right way to handle an unauthenticated request.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|