Archive

Posts Tagged ‘ASP.NET’

“Method Not Found” in ASP.NET Web API when using PUT and DELETE Verbs

Now that you have deployed your REST API and you are receiving “Method Not Found” exception / 404 exceptions when using PUT and DELETE verbs, while GET and POST is working absolutely fine. The fix is simple and needs small changes within IIS.

Open “Internet Information Services (IIS) Manager”, select the corresponding application and double-click on the “Handler Mappings” as shown below:

Image

Then select the “ExtensionlessUrlHandler-Integrated-4.0″ handler and double-click to edit this managed handler and click on “Request Restrictions…” button, as highlighted below:

Image

In the “Verbs” tab, select “One of the following verbs:” option and type-in the following verbs, “GET, HEAD, POST, DEBUG, PUT, DELETE”. Note: By default the “All verbs” option is selected by default.

Image

One final step is to ensure that your “web.config” contains “PUT” and “DELETE” in the verb attribute for “ExtensionlessUrl-Integrated-4.0” under the <handlers> section within <system.webServer>. Do a Find (Ctrl + F) if you have a really huge entries in “web.config” file.

<system.webServer>
  <handlers>
    <add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

You are good to go! As a practice I always perform a “Restart”, under “Manage Web Site” within the “Internet Information Services (IIS) Manager” window.

Advertisements
Categories: ASP.NET, C# Tags: , , , , , , ,

Uploading a File in ASP.Net Web API

Consider the following model file and a sample POST method.

namespace FeedbackService.Models
{
    public class Feedback
    {
        public string Id { get; set; }
        public string EmailId { get; set; }
        public string Comment { get; set; }
        public string PageUrl { get; set; }
        public byte[] Attachment { get; set; }
    }
}

The corresponding “Post” method is as given below.

        public HttpResponseMessage Post([FromBody] Feedback value)
        {
            try
            {
                return ModelState.IsValid ? Request.CreateResponse(_wrapper.CreateFeedback(value) ? HttpStatusCode.Created : HttpStatusCode.InternalServerError, value) : Request.CreateResponse(HttpStatusCode.BadRequest, value);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

In the above scenario, the file to be uploaded is converted to byte array first and then this request was posted from an html page. The first issue we encountered was “Maximum content length exceeded” and to troubleshoot this issue, we have to add the following entries in “web.config”

<!-- To be added under <system.web> -->
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" executionTimeout="3600" />

<!-- To be added under <system.webServer> -->
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>

The above said error went off, but there was new issue wherein the file upload was taking more time, That’s when we tried doing this the other way, we modified the “POST” method to include the following:

       public HttpResponseMessage Post()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

            try
            {
                var httpRequest = HttpContext.Current.Request;

                // Check if any file(s) have been uploaded
                if (httpRequest.Files.Count > 0)
                {
                    // Get file content as byte array
                    MemoryStream ms = new MemoryStream();
                    httpRequest.Files[0].InputStream.CopyTo(ms);
                    byte[] fileContent = ms.ToArray();

                    // Populate Feedback object
                    Feedback feedback = new Feedback();
                    feedback.PrototypeId = httpRequest.Form["prototypeId"];
                    feedback.PageUrl = httpRequest.Form["pageURL"];
                    feedback.EmailId = httpRequest.Form["emailId"];
                    feedback.Comment = httpRequest.Form["comment"];
                    feedback.Attachment = fileContent;

                    // Call the wrapper method
                    if (_wrapper.CreateFeedback(feedback))
                        return Request.CreateResponse(HttpStatusCode.Created);
                }
                else
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }

                // Return status indicating that the server refuses to fulfill request
                return Request.CreateResponse(HttpStatusCode.Forbidden);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }

and to test this, we created the following sample html file

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Feedback Test Form</title>
    <style type="text/css">
            table.bottomBorder {
                border-collapse: collapse;
            }
            table.bottomBorder td, table.bottomBorder th {
                border-bottom: 1px dotted black;
                padding: 5px;
            }
    </style>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="http://localhost:62465/api/feedback" id="feedbackForm" novalidate="novalidate">
        <fieldset>
            <legend><b>Submit Feedback</b></legend>
            <table class="bottomBorder">
                <tr>
                    <td>Prototype ID:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="prototypeId" id="prototypeId" value="59938fe1-d80a-4534-8a7a-01977dab8370"></td>
                </tr>
                <tr>
                    <td>Page URL:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="pageURL" id="pageURL" value="http://localhost:62465/PostFeedback.html"></td>
                </tr>
                <tr>
                    <td>Email ID:</td>
                    <td><input type="text" style="width: 320px; color: grey;" name="emailId" id="emailId" value="test@test.com"></td>
                </tr>
                <tr>
                    <td>Comment:</td>
                    <td><textarea name="comment" style="width: 320px; color: grey;" cols="30" rows="4">This page is super awesome!</textarea></td>
                </tr>
                <tr>
                    <td>File Attachment:</td>
                    <td><input type="file" style="width: 320px; color: grey;" name="fileAttachment" id="fileAttachment"></td>
                </tr>
            </table>
            <p>
                <input type="submit" value="Submit Feedback" id="btnUpload">
            </p>
        </fieldset>
    </form>
</body>
</html>

The above is just a sample implementation of uploading a file in ASP.Net Web API as well as an example of sending HTML form data.

Categories: ASP.NET, C# Tags: , , , , , ,

ASP.NET MVC2 Basics and Introduction

September 30, 2011 Leave a comment

A very nice video on ASP.NET MVC2 by “Scott Hanselman”, covers the introduction and basics and gives a very clear understanding about this pattern.

Categories: ASP.NET, C# Tags: , , ,

Launching an Infopath form with a button click

March 22, 2010 2 comments

When an Infopath form is published to Sharepoint Form Library, the only way to open a new form is either my navigating to the corresponding sharepoint library and click “New” or by clicking on the “Fill Out This Form” menu.

In order to open a new Infopath Form elsewhere in the Sharepoint site, you can use the below script and use a button click to achieve the same. As shown in the script below all you need is the sharepoint document library link.

<script type="text/vbscript" language="vbscript">
	Dim urlLibrary
	Dim urlTemplate
	
	urlLibrary = "http://sharepoint/sites/teamsite/DocLibrary"
	urlTemplate = urlLibrary + "/forms/template.xsn"

	Sub CreateNewInfoPathDocument
	  dim objOpenXMLDocuments
	  set objOpenXMLDocuments = Createobject("SharePoint.OpenXMLDocuments")
	  objOpenXMLDocuments.CreateNewDocument2 window, urlTemplate, urlLibrary
	End Sub
</script>

<!--Button Code-->

<button onclick="CreateNewInfoPathDocument()">Create New</button>

IIS Server Variables

November 3, 2009 2 comments

IIS server variables provide information about the server, the connection with the client, and the current request on the connection.

IIS server variables are not the same as environment variables.

Paste the code given below in your asp.net web page [HTML Design] to see the information associated for each of the iis server variables.

<%Response.Write(HttpContext.Current.Request.ServerVariables["ALL_HTTP"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["ALL_RAW"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["APPL_MD_PATH"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["AUTH_TYPE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["AUTH_PASSWORD"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["AUTH_USER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_COOKIE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_FLAGS"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_ISSUER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_KEYSIZE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_SECRETKEYSIZE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_SERIALNUMBER"]); %>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_SERVER_ISSUER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CERT_SERVER_SUBJECT"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CONTENT_LENGTH"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["CONTENT_TYPE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["GATEWAY_INTERFACE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTPS"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTPS_KEYSIZE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTPS_SECRETKEYSIZE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTPS_SERVER_ISSUER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTPS_SERVER_SUBJECT"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["INSTANCE_ID"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["INSTANCE_META_PATH"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["LOGON_USER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["PATH_INFO"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["PATH_TRANSLATED"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["QUERY_STRING"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["REMOTE_HOST"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["REQUEST_METHOD"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SCRIPT_MAP"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SCRIPT_NAME"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SERVER_NAME"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SERVER_PORT"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SERVER_PROTOCOL"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["SERVER_SOFTWARE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["URL"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_CONNECTION"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_HOST"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_REFERER"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_COOKIE"]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_UA_CPU "]);%>
<%Response.Write(HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_ENCODING"]);%>

References: http://msdn.microsoft.com/en-us/library/ms524602.aspx

%d bloggers like this: