I am getting this error (at the bottom) when I try to run this code using a generic handler
Jquery Code
$.post("CheckUserName.ashx?username=Aaron902",
function (result) {
$('#username_availability_result').html('Name already exist!');
if (result == "exists") {
$('#username_availability_result').html('Name already exist!');
}
else {
$('#username_availability_result').html('Still available');
}
});
Handler Code
public void ProcessRequest(HttpContext context)
{
string user_name = context.Request.QueryString["username"];
string output = "here";
output = CheckUserNameAvailability(user_name);
context.Response.Write(output);
context.Response.End();
}
Server Error in '/' Application.
Parser Error Description: An error occurred during the parsing of a
resource required to service this request. Please review the
following specific parse error details and modify your source file
appropriately.
Parser Error Message: Could not create type 'Dating.CheckUserName'.
Source Error: Line 1: <%# WebHandler Language="C#"
CodeBehind="CheckUserName.ashx.cs" class="Dating.CheckUserName" %>
Source File: /CheckUserName.ashx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.237
I found a fix to my issue although I am not sure why it works this way and not the original way. All I did was remove the code behind file and put all the code that was there into the ashx file instead of having it in the ashx.cs file.
Of course I removed the directive CodeBehind="CheckUserName.ashx.cs"
Related
I'm using Asp.Net MVC 5 and the bundling and minification system from System.Web.Optimization 1.1.0.0:
bundles.Add(new ScriptBundle("~/angularLibraries").Include(
......
));
and then to render the Bundle:
#Scripts.Render("~/angularLibraries")
From time to time I manually check the state of my bundles by opening the corresponding url in the browser, and sometimes I find them with errors. Example:
/* Minification failed. Returning unminified contents.
(262,145-152): run-time error JS1019: Can't have 'break' outside of loop: break a
(40,297-304): run-time error JS1019: Can't have 'break' outside of loop: break a
*/
Because the bundling mechanism returns the unminified contents when the minification fails, I'm unaware of the error until I manually open that bundle in a browser.
How can I setup the Bundling system to raise an exception when minification fails so I can immediately be aware of the error?
Found a solution. I have created a custom class that derives from ScriptBundle and overrides the method ApplyTransforms:
public class CustomScriptBundle : ScriptBundle
{
public CustomScriptBundle(string virtualPath)
: base(virtualPath)
{
}
public CustomScriptBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath)
{
}
public override BundleResponse ApplyTransforms(BundleContext context, string bundleContent, IEnumerable<BundleFile> bundleFiles)
{
BundleResponse bundleResponse = base.ApplyTransforms(context, bundleContent, bundleFiles);
if (bundleResponse.Content.StartsWith("/* Minification failed. Returning unminified contents."))
ExceptionManager.LogMessage("Minification failed for following bundle: " + context.BundleVirtualPath);
return bundleResponse;
}
}
I ended up logging a message (an receiving an email notification from Elmah) and not throwing an exception because I have minification enabled by default only on production, and the app will continue working ok anyway.
If you throw an exception, you'll see it like this:
This solution is also applicable for StyleBundle.
I'm using ASP.NET MVC default account system and recently when I try to login or register I'm getting this error:
Server Error in '/' Application.
Illegal characters in path.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Illegal characters in
path.
Source Error:
Line 46: if (ModelState.IsValid)
Line 47: {
Line 48: var user = await UserManager.FindAsync(model.UserName, model.Password);
Line 49: if (user != null)
Line 50: {
Source File:
c:\Users\u1152923\Desktop\newsWebApplication\newsWebApplication\Controllers\AccountController.cs Line: 48
No changes have been made to the AccountController.cs recently, so I dont understand where the problem has come from.
It's possible a change to web.config could have caused the error. The full web.config is below:
http://pastebin.com/iMviLJGS
Any help is appreciated.
I have managed to fix it! The problem infact comes from the IdentityModel.cs
Make sure the below is referencing the correct connection!
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
Thanks all for your help.
I am using a JavaScript plug-in and if there is an error it expects format like;
{error: 'You are not allowed to upload such a file.'}
In my MVC Web API I am throwing error like;
var error = string.Format("An error has been occured. Please try again later.");
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error));
and it is represented in HTTP response like below;
{"Message":"An error has been occured. Please try again later."}
how can I achieve to return in first way?
You can create an anonymous object
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.InternalServerError,new { error = "your error message here!"}));
I'm building an ASP.NET Web API endpoint that accepts 'multipart/form-data' requests. I implemented it as described in this article using .NET Framework 4.5 and Web API 2.1. A simplified version of the action method I created, looks like this:
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var rootPath = System.Configuration.ConfigurationManager.AppSettings["StorageLocation"].ToString();
var provider = new MultipartFormDataStreamProvider(rootPath);
var response = Request.CreateResponse(HttpStatusCode.OK);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// Imagine awesome logic here, unicorns and rainbows! Instead of that, we do the following:
response.Content = new StringContent("You uploaded " + provider.FileData.Count.ToString() + " files.");
}
catch (Exception e) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); }
return response;
}
Because the uploaded files can be very big (up to 2GiB), I want my requests to not be buffered by ASP.NET, thus avoiding high memory usage. To realize this I told Web API to stream incoming requests, instead of buffering them, as described in this article. The custom WebHostBufferPolicySelector looks something like this:
public class CustomWebHostBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
System.Web.HttpContextBase contextBase = hostContext as System.Web.HttpContextBase;
if (contextBase != null && contextBase.Request.ContentType != null && contextBase.Request.ContentType.Contains("multipart")) return false;
else return base.UseBufferedInputStream(hostContext);
}
public override bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response)
{
return base.UseBufferedOutputStream(response);
}
}
I load this guy in the Global.asax, at application start, like this:
protected void Application_Start(object sender, EventArgs e)
{
// Here, other stuff got did.
GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new CustomWebHostBufferPolicySelector());
}
Alright, the board is set, lets get the pieces moving. If I don't use my CustomWebHostBufferPolicySelector, everything works just fine. However, when its used, I get the following exception:
Message: "An error has occurred."
ExceptionMessage: "Error reading MIME multipart body part."
ExceptionType: "System.IO.IOException"
StackTrace: " at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()\ \ --- End of stack trace from previous location where exception was thrown ---\ \ at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\ \ at ..."
With the following inner exception:
Message: "An error has occurred."
ExceptionMessage: "Unable to read the entity body in Bufferless mode. The request stream has already been buffered."
ExceptionType: "System.InvalidOperationException"
StackTrace: " at System.Web.Http.WebHost.HttpControllerHandler.<>c__DisplayClass13.<GetStreamContent>b__10()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.get_StreamContent()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.CreateContentReadStreamAsync()\ \ at System.Net.Http.HttpContent.ReadAsStreamAsync()\ \ at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()"
It looks like the request is still buffered somehow, by something else. Is there another place in the ASP.NET pipeline I should be looking? Or even IIS maybe? What are the other places in this request's lifecycle where it can be buffered, and how do I control them?
In an attempt to make the problem more clear and shareable with others, I created a simple project to try and reproduce the problem. While doing this I found the answer: disable all kinds of tracing.
In my case I had ASP.NET's own tracing functionality enabled, and also Glimpse. Both of these buffer the request before it arrives at the Web API action.
For completeness' sake, here the proper way to turn them off in your Web.Config, while testing and in production.
<configuration>
<system.web>
<trace enabled="false" />
</system.web>
<glimpse defaultRuntimePolicy="Off">
</glimpse>
</configuration>
In my case, these two were the culprits, but I can imagine there may be others, so be wary of this.
I'm using Uploadify within my ASP.NET 4 project. I'm using an HttpHandler to receive the posted file and process it into a directory. The upload is working fine. However, I wanted to handle any errors I could within my HttpHandler, and I am finding it impossible.
I have the processing of the file wrapped in a try catch, but I am never able to return an error message. I always receive the IO Error: Error #2038
try
{
UploadFiles(context.Request.Files);
}
catch(Exception ex)
{
context.Response.Write(ex.Message);
}
Is it not possible to return custom errors back to the client when using SWFUpload/Uploadify?
Take alook at here
uploadify error handling
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}