GridView inside update panel – link button not firing

aspx page:-
--Gridview 

<ItemTemplate>
<asp:LinkButton ID="lbtnDownload" runat="server" Text="Download" OnClick="lbtnDownload_Click" 
OnDataBinding="LB_DataBinding"></asp:LinkButton>
</ItemTemplate>

Now in your codebehind:

protected void LB_DataBinding(object sender, EventArgs e)
{
   LinkButton lbDownload = (LinkButton) sender;
   ScriptManager scriptMgr = (ScriptManager)Page.Master.FindControl("scriptMgrID");
   scriptMgr.RegisterPostBackControl(lbDownload);
}

 

Leave a Comment

Webbrowser using ie10 c# winform

I had the same problem that my app wrote the value to “HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION”.

I changed LocalMachine to CurrentUser and now it works.

string executablePath =Environment.GetCommandLineArgs()[0];
string executableName =System.IO.Path.GetFileName(executablePath);
RegistryKey registrybrowser =Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",true);if(registrybrowser ==null){RegistryKey registryFolder =Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl",true);
 registrybrowser = registryFolder.CreateSubKey("FEATURE_BROWSER_EMULATION");}
registrybrowser.SetValue(executableName,0x02710,RegistryValueKind.DWord);
registrybrowser.Close();

Leave a Comment

Compare two or more column value randomized fromat using ASCII

Example :-

Create function dbo.fnAnswerUpdate (@UserAnswer nvarchar(1000),@CorrectAnswer nvarchar(1000))

Returns int As Begin

DECLARE @position int, @position1 int, @string varchar(200)

— Initialize the variables.

SET @position = 1

SET @position1 = 1

SET @string = @UserAnswer

Declare @a int set @a=0

WHILE @position <= DATALENGTH(@string)

BEGIN set @a+=(SELECT ASCII(SUBSTRING(@string, @position, 1)))

SET @position = @position + 1

End SET @position1 = 1

SET @string = @CorrectAnswer

Declare @b int

set @b=0

WHILE @position1 <= DATALENGTH(@string)

BEGIN set @b+=(SELECT ASCII(SUBSTRING(@string, @position1, 1)))

SET @position1 = @position1 + 1

End

if(@a=@b)

Begin

set @a=1

End

Else

Begin

set @a=2

End

return @a

End

Go

Select dbo.fnAnswerUpdate(‘A|B|C’,’B|D|A’)

1- Complete

2-Incomplete

Leave a Comment

Submit Login control button when I hit Enter

You can use the following to reference the button within the Login control template:

DefaultButton="Login$LoginButton"

Basically, you can define a DefaultButton not just on the Form level, but also on individual Panel level, as long as the focus is within the panel, the default button for the panel will be used if you hit “Enter”

Leave a Comment

Securing ASP.NET Web API using basic Authentication

Basic HTTP Authentication

In basic HTTP authentication the client passes their username and password in the HTTP request header. Typically, using this technique we encrypt user credentials string into base64 encoded string and decrypt this base64 encoded string into plain text. You can also use another encryption and decryption technique.

Custom Principal

Since WebAPI is build on the top of ASP.NET Framework, hence it can use ASP.NET Framework features like ASP.NET membership and provider. ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. For ASP.NET Web API, you can also create a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well as the current thread.

  1. publicclassCustomPrincipal:IPrincipal
  2. {
  3. publicIIdentityIdentity{ get;privateset;}
  4. publicboolIsInRole(string role)
  5. {
  6. if(roles.Any(r => role.Contains(r)))
  7. {
  8. returntrue;
  9. }
  10. else
  11. {
  12. returnfalse;
  13. }
  14. }
  15.  
  16. publicCustomPrincipal(string Username)
  17. {
  18. this.Identity=newGenericIdentity(Username);
  19. }
  20.  
  21. publicintUserId{ get;set;}
  22. public string FirstName{ get;set;}
  23. public string LastName{ get;set;}
  24. public string[] roles { get;set;}
  25. }

Now you can put this CustomPrincipal objects into the thread’s currentPrinciple property and into the HttpContext’s User property to accomplish your custom authentication and authorization process.

Custom ASP.NET Web API Authorization Filter

Like ASP.NET MVC, Web API also provides Authorization filter to authorize a user. This filter can be applied to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class exist in System.Web.Http namespace. You can customize this filter by overriding OnAuthorization() method as shown below:

  1. //custom authorize filter attribute
  2. publicclassCustomAuthorizeAttribute:AuthorizeAttribute
  3. {
  4. privateconst string BasicAuthResponseHeader=“WWW-Authenticate”;
  5. privateconst string BasicAuthResponseHeaderValue=“Basic”;
  6. readonly DataContextContext=newDataContext();
  7.  
  8. public string UsersConfigKey{ get;set;}
  9. public string RolesConfigKey{ get;set;}
  10.  
  11. protectedCustomPrincipalCurrentUser
  12. {
  13. get {returnThread.CurrentPrincipal as CustomPrincipal;}
  14. set{Thread.CurrentPrincipal= value as CustomPrincipal;}
  15. }
  16.  
  17. public override voidOnAuthorization(HttpActionContext actionContext)
  18. {
  19. try
  20. {
  21. AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;
  22.  
  23. if(authValue != null &&!String.IsNullOrWhiteSpace(authValue.Parameter)&& authValue.Scheme==BasicAuthResponseHeaderValue)
  24. {
  25. Credentials parsedCredentials =ParseAuthorizationHeader(authValue.Parameter);
  26.  
  27. if(parsedCredentials != null)
  28. {
  29. var user =Context.Users.Where(u => u.Username== parsedCredentials.Username&& u.Password== parsedCredentials.Password).FirstOrDefault();
  30. if(user != null)
  31. {
  32. var roles = user.Roles.Select(m => m.RoleName).ToArray();
  33. var authorizedUsers =ConfigurationManager.AppSettings[UsersConfigKey];
  34. var authorizedRoles =ConfigurationManager.AppSettings[RolesConfigKey];
  35.  
  36. Users=String.IsNullOrEmpty(Users)? authorizedUsers :Users;
  37. Roles=String.IsNullOrEmpty(Roles)? authorizedRoles :Roles;
  38.  
  39. CurrentUser=newCustomPrincipal(parsedCredentials.Username, roles);
  40.  
  41. if(!String.IsNullOrEmpty(Roles))
  42. {
  43. if(!CurrentUser.IsInRole(Roles))
  44. {
  45. actionContext.Response= actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
  46. actionContext.Response.Headers.Add(BasicAuthResponseHeader,BasicAuthResponseHeaderValue);
  47. return;
  48. }
  49. }
  50.  
  51. if(!String.IsNullOrEmpty(Users))
  52. {
  53. if(!Users.Contains(CurrentUser.UserId.ToString()))
  54. {
  55. actionContext.Response= actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
  56. actionContext.Response.Headers.Add(BasicAuthResponseHeader,BasicAuthResponseHeaderValue);
  57. return;
  58. }
  59. }
  60.  
  61. }
  62. }
  63. }
  64. }
  65. catch(Exception)
  66. {
  67. actionContext.Response= actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
  68. actionContext.Response.Headers.Add(BasicAuthResponseHeader,BasicAuthResponseHeaderValue);
  69. return;
  70.  
  71. }
  72. }
  73.  
  74. privateCredentialsParseAuthorizationHeader(string authHeader)
  75. {
  76. string[] credentials =Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[]{‘:’});
  77.  
  78. if(credentials.Length!=2|| string.IsNullOrEmpty(credentials[0])|| string.IsNullOrEmpty(credentials[1]))
  79. return null;
  80.  
  81. returnnewCredentials(){Username= credentials[0],Password= credentials[1],};
  82. }
  83. }
  84. //Client credential
  85. publicclassCredentials
  86. {
  87. public string Username{ get;set;}
  88. public string Password{ get;set;}
  89. }

Applying CustomAuthorize attribute

To make secure your service, decorate your Web API controllers with CustomAuthorize attribute as defined above and specify the uses or roles to access specific service actions/methods. The below product service action Getproduct can be access only by Admin users.

  1. publicclassProductController:ApiController
  2. {
  3. [CustomAuthorize(Roles=“Admin”)]
  4. publicHttpResponseMessageGetproducts()
  5. {
  6. var products =newProduct[]
  7. {
  8. newProduct()
  9. {
  10. Id=1,
  11. Name=“Soap”,
  12. Price=25.12
  13. },
  14. newProduct()
  15. {
  16. Id=2,
  17. Name=“Shampoo”,
  18. Price=25.12
  19. }
  20. };
  21.  
  22. var response =Request.CreateResponse<ienumerable>(HttpStatusCode.OK, products);
  23. <ienumerablereturn response;
  24. <ienumerable}
  25. <ienumerable}

Calling Web API and passing client credential from ASP.NET MVC

  1. publicclassHomeController:Controller
  2. {
  3. //
  4. // GET: /Home/
  5. publicActionResultIndex()
  6. {
  7. string FullName=User.FirstName+” “+User.LastName;
  8. HttpClient client =newHttpClient();
  9. string authInfo =“admin”+“:”+“123456”;
  10. authInfo =Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
  11. client.DefaultRequestHeaders.Authorization=newAuthenticationHeaderValue(“Basic”, authInfo);
  12.  
  13. client.BaseAddress=newUri(http://localhost:63173/&#8221;);
  14.  
  15. HttpResponseMessage response = client.GetAsync(“api/product/”).Result;
  16. if(response.IsSuccessStatusCode)
  17. {
  18. // Parse the response body. Blocking!
  19. var data = response.Content.ReadAsAsync<ienumerable>().Result;
  20. <ienumerablereturnView();
  21. <ienumerable}
  22. <ienumerablereturnView();
  23. <ienumerable}
  24. <ienumerable}

Leave a Comment

Passing multiple complex type parameters to ASP.NET Web API

Asp.Net Web API introduces a new powerful REST API which can be consume by a broad range of clients including browsers, mobiles, iphone and tablets. It is focused on resource based solutions and HTTP verbs.

Asp.Net Web API has a limitation while sending data to a Web API controller. In Asp.Net Web API you can pass only single complex type as a parameter. But sometimes you may need to pass multiple complex types as parameters, how to achieve this?

You can also achieve this task by wrapping your Supplier and Product classes into a wrapper class and passing this wrapper class as a parameter, but using this approach you need to make a new wrapper class for each actions which required complex types parameters. In this article, I am going to explain another simple approach using ArrayList.

Let’s see how to achieve this task. Suppose you have two classes – Supplier and Product as shown below –

  1. publicclassProduct
  2. {
  3. publicintProductId{ get;set;}
  4. public string Name{ get;set;}
  5. public string Category{ get;set;}
  6. public decimal Price{ get;set;}
  7. }
  8.  
  9. publicclassSupplier
  10. {
  11. publicintSupplierId{ get;set;}
  12. public string Name{ get;set;}
  13. public string Address{ get;set;}
  14. }

In your Asp.Net MVC controller you are calling your Web API and you need to pass both the classes objects to your Web API controller.

Method 1 : Using ArrayList

For passing multiple complex types to your Web API controller, add your complex types to ArrayList and pass it to your Web API actions as given below-

  1. publicclassHomeController:Controller
  2. {
  3. publicActionResultIndex()
  4. {
  5. HttpClient client =newHttpClient();
  6. Uri baseAddress =newUri(http://localhost:2939/&#8221;);
  7. client.BaseAddress= baseAddress;
  8. ArrayList paramList =newArrayList();
  9. Product product =newProduct{ProductId=1,Name=“Book”,Price=500,Category=“Soap”};
  10. Supplier supplier =newSupplier{SupplierId=1,Name=“AK Singh”,Address=“Delhi”};
  11. paramList.Add(product);
  12. paramList.Add(supplier);
  13. HttpResponseMessage response = client.PostAsJsonAsync(“api/product/SupplierAndProduct”, paramList).Result;
  14. if(response.IsSuccessStatusCode)
  15. {
  16. returnView();
  17. }
  18. else
  19. {
  20. returnRedirectToAction(“About”);
  21. }
  22. }
  23. publicActionResultAbout()
  24. {
  25. returnView();
  26. }
  27. }

Now, on Web API controller side, you will get your complex types as shown below.

Now deserialize your complex types one by one from ArrayList as given below-

  1. publicclassProductController:ApiController
  2. {
  3. [ActionName(“SupplierAndProduct”)]
  4. [HttpPost]
  5. publicHttpResponseMessageSuppProduct(ArrayList paramList)
  6. {
  7. if(paramList.Count>0)
  8. {
  9. Product product =Newtonsoft.Json.JsonConvert.DeserializeObject(paramList[0].ToString());
  10. Supplier supplier =Newtonsoft.Json.JsonConvert.DeserializeObject(paramList[1].ToString());
  11. //TO DO: Your implementation code
  12. HttpResponseMessage response =newHttpResponseMessage{StatusCode=HttpStatusCode.Created};
  13. return response;
  14. }
  15. else
  16. {
  17. HttpResponseMessage response =newHttpResponseMessage{StatusCode=HttpStatusCode.InternalServerError};
  18. return response;
  19. }
  20. }
  21. }

Method 2 : Using Newtonsoft JArray

For passing multiple complex types to your Web API controller, you can also add your complex types to JArray and pass it to your Web API actions as given below-

  1. publicclassHomeController:Controller
  2. {
  3. publicActionResultIndex()
  4. {
  5. HttpClient client =newHttpClient();
  6. Uri baseAddress =newUri(http://localhost:2939/&#8221;);
  7. client.BaseAddress= baseAddress;
  8. JArray paramList =newJArray();
  9. Product product =newProduct{ProductId=1,Name=“Book”,Price=500,Category=“Soap”};
  10. Supplier supplier =newSupplier{SupplierId=1,Name=“AK Singh”,Address=“Delhi”};
  11. paramList.Add(JsonConvert.SerializeObject(product));
  12. paramList.Add(JsonConvert.SerializeObject(supplier));
  13. HttpResponseMessage response = client.PostAsJsonAsync(“api/product/SupplierAndProduct”, paramList).Result;
  14. if(response.IsSuccessStatusCode)
  15. {
  16. returnView();
  17. }
  18. else
  19. {
  20. returnRedirectToAction(“About”);
  21. }
  22. }
  23. publicActionResultAbout()
  24. {
  25. returnView();
  26. }
  27. }

Note

Don’t forget to add reference of Newtonsoft.Json.dll to your ASP.NET MVC project and WebAPI as well.

Now, on Web API controller side, you will get your complex types within JArray as shown below.

Now deserialize your complex types one by one from JArray as given below-

  1. publicclassProductController:ApiController
  2. {
  3. [ActionName(“SupplierAndProduct”)]
  4. [HttpPost]
  5. publicHttpResponseMessageSuppProduct(JArray paramList)
  6. {
  7. if(paramList.Count>0)
  8. {
  9. Product product =JsonConvert.DeserializeObject(paramList[0].ToString());
  10. Supplier supplier =JsonConvert.DeserializeObject(paramList[1].ToString());
  11. //TO DO: Your implementation code
  12. HttpResponseMessage response =newHttpResponseMessage{StatusCode=HttpStatusCode.Created};
  13. return response;
  14. }
  15. else
  16. {
  17. HttpResponseMessage response =newHttpResponseMessage{StatusCode=HttpStatusCode.InternalServerError};
  18. return response;
  19. }
  20. }
  21. }

In this way, you can easily pass your complex types to your Web API. There are two solution, there may be another one as well.

Leave a Comment

Comparing Asp.Net Web API Routing and Asp.Net MVC Routing

As you know, Routing is a pattern matching system that monitor the incoming request and figure out what to do with that request. A URL pattern is matched against the routes patterns defined in the Route dictionary in an Order and the first match wins. This means the first route which successfully matches a controller, action, and action parameters defined in the URL will call into the specified controller and action.

Asp.Net MVC application and Asp.Net Web API must have at least one route defined in order to function. Hence, Visual Studio templates defined for MVC and Web API must have a default route. Now let’s understand the difference between Asp.Net MVC and Asp.Net Web API.

Default Route Pattern

The default route pattern for a Web API Project is defined as follows-

  1. config.Routes.MapHttpRoute(
  2. name:“DefaultApi”,//route name
  3. routeTemplate:“api/{controller}/{id}”,//route pattern
  4. defaults:new{ id =RouteParameter.Optional}//parameter default values
  5. );

The literal api at the beginning of the Web API route pattern, makes it distinct from the standard MVC route. This is not mandatory but it is a good convention to differ Web API route from MVC route.

In Web API route pattern {action} parameter is optional but you can include an {action} parameter. Also, the action methods defined on the controller must be have an HTTP action verb as a prefix to the method name in order to work. So, you can also define the route for Web API as follows-

  1. config.Routes.MapHttpRoute(
  2. name:“DefaultApi”,//route name
  3. routeTemplate:“api/{controller}/{action}/{id}”,//route pattern
  4. defaults:new{ id =RouteParameter.Optional}//parameter default values
  5. );

The default route pattern for an Asp.Net MVC Project is defined as follows-

  1. routes.MapRoute(
  2. name:“Default”,//route name
  3. url:“{controller}/{action}/{id}”,//route pattern
  4. defaults:new
  5. {
  6. controller =“Home”,
  7. action =“Index”,
  8. id =UrlParameter.Optional
  9. }//parameter default values
  10. );

As you have seen there is no literal before at the beginning of the Asp.Net MVC route pattern but you can add if you wish.

Route Processing

In Web API route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the API controller must either have the HTTP action verbs (GET, POST, PUT, DELETE) or have one of the HTTP action verbs as a prefix for the Actions methods name as given below-

  1. publicclassValuesController:ApiController
  2. {
  3. // GET api/
  4. publicIEnumerableGet()
  5. {
  6. returnnew string[]{“value1”,“value2”};
  7. }
  8. // GET api//5
  9. public string Get(int id)
  10. {
  11. return“value”;
  12. }
  13. // POST api/
  14. publicvoidPost([FromBody]string value)
  15. {
  16. }
  17. // PUT api//5
  18. publicvoidPut(int id,[FromBody]string value)
  19. {
  20. }
  21. // DELETE api//5
  22. publicvoidDelete(int id)
  23. {
  24. }
  25. }
  26. // OR You can also defined above API Controller as Verb Prefix
  27. publicclassValuesController:ApiController
  28. {
  29. // GET api/values
  30. publicIEnumerableGetValues()
  31. {
  32. returnnew string[]{“value1”,“value2”};
  33. }
  34. // GET api/values/5
  35. public string GetValues(int id)
  36. {
  37. return“value”;
  38. }
  39. // POST api/values
  40. publicvoidPostValues([FromBody]string value)
  41. {
  42. }
  43. // PUT api/values/5
  44. publicvoidPutValues(int id,[FromBody]string value)
  45. {
  46. }
  47. // DELETE api/values/5
  48. publicvoidDeleteValues(int id)
  49. {
  50. }
  51. }

In Asp.Net MVC route processing the URLs map to a controller, and then to the action which matches the HTTP verb of the request and the most parameters of the request is selected. The Action methods defined in the MVC controller do not have HTTP action verbs as a prefix for the Actions methods but they have name like as normal method as shown below-

  1. publicclassHomeController:Controller
  2. {
  3. // GET: /Home/Index
  4. publicActionResultIndex()//method – Index
  5. {
  6. // To Do:
  7. returnView();
  8. }
  9.  
  10. // Post: /Home/Index
  11. [HttpPost]
  12. publicActionResultIndex(LoginModel model, string id)
  13. {
  14. // To Do:
  15. returnView();
  16. }
  17. }

In MVC, by default HTTP verb is GET for using others HTTP verbs you need defined as an attribute but in Web API you need to define as an method’s name prefix.

Complex Parameter Processing

Unlike MVC, URLs in Web API cannot contain complex types. Complex types must be placed in the HTTP message body and there should be only one complex type in the body of an HTTP message.

Base Library

Web API controllers inherit from System.Web.Http.Controller, but MVC controllers inherit fromSystem.Web.Mvc.Controller. Both the library are different but acts in similar fashion.

Leave a Comment

How to pass javascript complex object to ASP.NET Web Api and MVC

ASP.NET Web API is one of the most powerful recent addition to ASP.NET framework. Sometimes, you have to post a form data using jQuery-JSON to Web API or MVC method, which have so many input fields. Passing each and every input field data as a separate parameter is not good practice, even when you have a strongly typed-view. The best practice is, pass a complex type object for all the input fields to the server side to remove complexity.

In this article, I am going to explain you how can you pass complex types object to the Web API and MVC method to remove complexity at server side and make it simple and useful.

Model Classes

Suppose you have the following Product class and repository for product.

  1. publicclassProduct
  2. {
  3. publicintId{ get;set;}
  4. public string Name{ get;set;}
  5. public string Category{ get;set;}
  6. public decimal Price{ get;set;}
  7. }
  8.  
  9. interface IProductRepository
  10. {
  11. ProductAdd(Product item);
  12. //To Do : Some Stuff
  13. }
  14.  
  15. publicclassProductRepository:IProductRepository
  16. {
  17. privateList<Product> products =newList<Product>();
  18. privateint _nextId =1;
  19.  
  20. publicProductRepository()
  21. {
  22. // Add products for the Demonstration
  23. Add(newProduct{Name=“Computer”,Category=“Electronics”,Price=23.54M});
  24. Add(newProduct{Name=“Laptop”,Category=“Electronics”,Price=33.75M});
  25. Add(newProduct{Name=“iPhone4”,Category=“Phone”,Price=16.99M});
  26. }
  27.  
  28. publicProductAdd(Product item)
  29. {
  30. if(item == null)
  31. {
  32. thrownewArgumentNullException(“item”);
  33. }
  34. // TO DO : Code to save record into database
  35. item.Id= _nextId++;
  36. products.Add(item);
  37.  
  38. return item;
  39. }
  40. //To Do : Some Stuff
  41. }

View (Product.cshtml)

  1. <scripttype=“text/javascript”>
  2. //Add New Item by Web API
  3. $(“#Save”).click(function(){
  4.  
  5. //Making complex type object
  6. varProduct={
  7. Id:“0”,
  8. Name: $(“#Name”).val(),
  9. Price: $(“#Price”).val(),
  10. Category: $(“#Category”).val()
  11. };
  12. if(Product.Name!=“”&&Product.Price!=“”&&Product.Category!=“”){
  13. //Convert javascript object to JSON object
  14. var DTO = JSON.stringify(Product);
  15. $.ajax({
  16. url:‘api/product’,//calling Web API controller product
  17. cache:false,
  18. type:‘POST’,
  19. contentType:‘application/json; charset=utf-8’,
  20. data: DTO,
  21. dataType:“json”,
  22. success:function(data){
  23. alert(‘added’);
  24. }
  25. }).fail(
  26. function(xhr, textStatus, err){
  27. alert(err);
  28. });
  29.  
  30. }
  31. else{
  32. alert(‘Please Enter All the Values !!’);
  33. }
  34.  
  35. });
  36.  
  37. </script>
  38. <div>
  39. <div>
  40. <h2>Add New Product</h2>
  41. </div>
  42. <div>
  43. <labelfor=“name”>Name</label>
  44. <inputtype=“text”id=“Name”title=“Name”/>
  45. </div>
  46.  
  47. <div>
  48. <labelfor=“category”>Category</label>
  49. <inputtype=“text”id=“Category”title=“Category”/>
  50. </div>
  51.  
  52. <div>
  53. <labelfor=“price”>Price</label>
  54. <inputtype=“text”id=“Price”title=“Price”/>
  55. </div>
  56. <br/>
  57. <div>
  58. <buttonid=“Save”>Save</button>
  59. <buttonid=“Reset”>Reset</button>
  60. </div>
  61. </div>

Web API Controller

  1. publicclassProductController:ApiController
  2. {
  3. static readonly IProductRepository repository =newProductRepository();
  4. publicProductPostProduct(Product item)
  5. {
  6. return repository.Add(item);
  7. }
  8. }

How it work ?

The same thing you have to done with MVC while calling MVC controller method using jQuery-JSON.

Leave a Comment

Difference between ASP.NET MVC and ASP.NET Web API

While developing your web application using MVC, many developers got confused when to use Web API, since MVC framework can also return JSON data by using JsonResult and can also handle simple AJAX requests. In previous article, I have explained the Difference between WCF and Web API and WCF REST and Web Service and when to use Web API over others services. In this article, you will learn when to use Web API with MVC.

Asp.Net Web API VS Asp.Net MVC

  1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
  2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it’s about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
  3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don’t worry about that. MVC only return data in JSON format using JsonResult.
  4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
  5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.
  6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will be called Web API self hosting.
  7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since boths are different.
  8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.

Leave a Comment

What is Web API and why to use it ?

Asp.Net Web API is a framework for building HTTP services that can be consume by a broad range of clients including browsers, mobiles, iphone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like Asp.Net WebForms. It can also be used as an stand-alone Web services application.

Why Asp.Net Web API (Web API) ?

Today, a web-based application is not enough to reach it’s customers. People are very smart, they are using iphone, mobile, tablets etc. devices in its daily life. These devices also have a lot of apps for making the life easy. Actually, we are moving from the web towards apps world.

So, if you like to expose your service data to the browsers and as well as all these modern devices apps in fast and simple way, you should have an API which is compatible with browsers and all these devices.

For example twitter,facebook and Google API for the web application and phone apps.

Web API is the great framework for exposing your data and service to different-different devices. Moreover Web API is open source an ideal platform for building REST-ful services over the .NET Framework. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats) and you don’t need to define any extra config settings for different devices unlike WCF Rest service.

Web API Features

  1. It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE.
  2. Responses have an Accept header and HTTP status code.
  3. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.
  4. It may accepts and generates the content which may not be object oriented like images, PDF files etc.
  5. It has automatic support for OData. Hence by placing the new [Queryable] attribute on a controller method that returns IQueryable, clients can use the method for OData query composition.
  6. It can be hosted with in the applicaion or on IIS.
  7. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection that makes it more simple and robust.

Why to choose Web API ?

  1. If we need a Web Service and don’t need SOAP, then ASP.Net Web API is best choice.
  2. It is Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.
  3. It doesn’t have tedious and extensive configuration like WCF REST service.
  4. Simple service creation with Web API. With WCF REST Services, service creation is difficult.
  5. It is only based on HTTP and easy to define, expose and consume in a REST-ful way.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. It is open source.

Leave a Comment

Older Posts »