web api in mvc 4

Hi All, I'm going to share the code sample for web api in mvc 4 using $.post() and $.getJSON() methods.

Today's, i have requirement to logging to errors using "web api in mvc 4 and jquery".

In the 1st step, code sample for $.post() and $.getJSON() methods

$.post() method

//POST() method used to post exceptions and Log too large data in the DB.
   $.post(‘/ExceptionLog/Logger’, { requestUrl: logsUrl, browserInfo: browser_version, cookiesInfo: cookies, error: errorInfo })
   .done(function (data) {
       console.log(data);
    })
   .fail(function (jqXHR, textStatus, errMsg) {
       console.log('Errors: ' + errMsg);

    });

$.getJSON() method

   //getJSON() method used to get exceptions and Log limited data in the DB.
   $.getJSON(‘/ExceptionLog/Logger’, { userId: Id})
   .done(function (data) {
       console.log(data);
    })
   .fail(function (jqXHR, textStatus, errMsg) {
       console.log('Errors: ' + errMsg);

    });

Note: 
1. In the above, we used to $.post() method for post to too large data in query string. 
2. In the above, we used to $.getJSON() method for post to limited data in query string.

In the 2st step, code sample for MVC 4

public class ExceptionLogController : Controller
{
  //ExceptionLog/Log.
  // Used to Insert exception logs in exception_log table.
  public void Logger(string requestUrl, string browserInfo, string cookiesInfo, string    error)
  {
       using (ExceptionLogDataContext dbContext = new ExceptionLogDataContext())
       {
            exception_log logger = new exception_log();
            logger.exceptionTime = DateTime.Now;
            logger.exceptionType = "Exception";
            logger.message = "Request Url : " + requestUrl + ", | Current Browser : "
            + browserInfo + ", | Client Cookies Information : " + cookiesInfo +
             ", | Exception Details : " + error;

            logger.title = "Exception while fetching to " + requestUrl;

            dbContext.exception_logs.InsertOnSubmit(logger);
            dbContext.SubmitChanges();
        }
    }
}


ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.