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

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.