I have an web api controller
using sport.BLL.Abstract;
using sport.BLL.Concrete;
using sport.DAL.Entities;
using sport.webApi.Models;
using AutoMapper;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.WebPages.Html;
namespace sport.webApi.Controllers
{
public class AccountManageController : ApiController
{
[HttpPost]
public System.Web.Mvc.ActionResult CreateAccount(CollaborateurModel item)
{
var user = new ApplicationUser { UserName = item.Username, Email = item.Email };
var result = UserManager.CreateAsync(user, item.Password);
if (result.Result.Succeeded)
{
var currentUser = UserManager.FindByName(item.Username);
var roleresult = UserManager.AddToRole(currentUser.Id, item.Role);
ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
entity.id_user_fk = currentUser.Id;
entity.is_deleted = false;
repo.CreateCollaborator(entity);
var response = new { Success = true };
return Json(response);
}
else
{
var errorResponse = new { Success = false, ErrorMessage = "error" };
return Json(errorResponse);
}
}
}
}
I got an error in this line :
return Json(response);
the Json Method is not recognized!!! when I googled about that I get this link which indicates that Json method is included in System.Web.Mvc. Even I try to import this namespace I get the same error?
So is the reason of this error?
How can I fix it?
The problem is that you are inheriting from ApiController but Json is a member of System.Web.Mvc.Controller.
Try using JsonResult:
return new JsonResult { data = yourData; }
You can set any object to a data as it will be serialized to a JSON.
For instance, if you need to return only a result of operation, you can use it this way:
return new JsonResult { data = true; } // or false
However, it is a good practice to describe a result class and return objects.
How can I fix it?
The reason is in the fact that you aren't inheriting from Controller but from ApiController, where the former has Json(object o) as a method in it's base class, but that doesn't actually matter, as there is a fundamental problem with your approach.
ApiController which is used with WebAPI isn't meant to return an ActionResult, which is a concept that belongs to MVC. Instead, you simply return your POCO and let the WebAPI framework handle serialization for you:
public object CreateAccount(CollaborateurModel item)
{
// Do stuff:
if (result.Result.Succeeded)
{
return new { Success = true }
}
else
{
return new { Success = false, ErrorMessage = "error" };
}
}
You can set your formatter configuration in your Global.asax.cs file, and tell it exactly which ones to use (in your case, you'll want the JsonMediaTypeFormatter).
Related
I have an error in this code. I deserialize a JSON file and stored that data in the database now I want to show that data from my database.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
Error is:
JSON can not be used like method.
What should I do?
Your contoller must be extend the base class Controller in which the Json() virtual method is available:
public class StudentController : Controller
{
// your code
}
To resolve this error you can try as below
public class StudentController : Controller
{
// your code
}
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var list = await context.StudentDto.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
What you need to do is to extend your StudentCotroller with Controller then put your code under that.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController:Controller
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
I am receiving the following error: The name 'Ok' does not exist in the current context.
How would I resolve this issue in my Controller API? Return Ok is already embedded in the controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using Newtonsoft.Json;
using WeatherTest.Models;
namespace WeatherChecker.Controllers
{
public class WeatherData
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=YOUR_API_KEY_HERE&units=metric");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);
// Error Here: ** The name 'Ok' does not exist in the current context **
return Ok(new
{
Temp = rawWeather.Main.Temp,
Summary = string.Join(",", rawWeather.Weather.Select(x => x.Main)),
City = rawWeather.Name
});
}
catch (HttpRequestException httpRequestException)
{
// Error Here: The name 'BadRequest' does not exist in the current context
return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
}
}
}
}
}
With Attribute routing feature, aspnet support POCO controller. It allow to use any class as controller. But you will we lose all utilities and helpers provided by framework base classes.
The class Controller inherite from ControllerBase and add view support. In your case, ControllerBase is enough.
public class WeatherData : ControllerBase // <-
{
// ...
}
i'm trying to get my apicontroller to work. But somehow i cannot return Json().
Here's the error message from the compiler:
Error CS0029 Cannot implicitly convert type
'System.Web.Http.Results.JsonResult<>'
to
'System.Web.Mvc.JsonResult' Opten.Polyglott.Web D:\Development\git\Opten.Polyglott\src\Opten.Polyglott.Web\Controllers\NewsletterApiController.cs
I cannot explain why it cannot convert the Json() to the ActionResult even the Json()inherits ActionResult.
Here's my controller:
using MailChimp;
using MailChimp.Helper;
using Opten.Polyglott.Web.Models;
using Opten.Umbraco.Common.Extensions;
using System.Configuration;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Web.WebApi;
namespace Opten.Polyglott.Web.Controllers
{
public class NewsletterApiController : UmbracoApiController
{
public ActionResult Subscribe(Newsletter newsletter)
{
bool isSuccessful = false;
if (ModelState.IsValid)
{
isSuccessful = SubscribeEmail(newsletter.Email);
}
return Json(new { isSuccess = isSuccessful });
}
}
}
Thanks for any help.
Your problem is within the usings as the UmbracoApiController most likely inherits from ApiController (from System.Web.Http) not Controller (from System.Web.Mvc) and thus they have different dependencies. To fix your problem first remove the
using System.Web.Mvc;
and put the
using System.Web.Http;
as for the return in this case that would be IHttpActionResult so you would have something as follows:
using MailChimp;
using MailChimp.Helper;
using Opten.Polyglott.Web.Models;
using Opten.Umbraco.Common.Extensions;
using System.Configuration;
using System.Web.Http;
using Umbraco.Core.Logging;
using Umbraco.Web.WebApi;
namespace Opten.Polyglott.Web.Controllers
{
public class NewsletterApiController : UmbracoApiController
{
public IHttpActionResult Subscribe(Newsletter newsletter)
{
bool isSuccessful = false;
if (ModelState.IsValid)
{
isSuccessful = SubscribeEmail(newsletter.Email);
}
return Json(new { isSuccess = isSuccessful });
}
}
}
Let me know if that works for you.
It seems your Json is using class in System.Web.Http, not in System.Web.Mvc. In this case, you can use this code:
return new JsonResult{ isSuccess = isSuccessful };
When using ActionResult using Response.StatusCode is a good practice:
public ActionResult SomeMethod()
{
try
{
// ...
// doing something here...
// ...
// success:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json(new { responseText = "OK" });
}
catch
{
// error:
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { responseText = "ERROR" });
}
}
Add the following line in your WebApiConfig.cs file:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
I would like to return camel-cased JSON data using Web API. I inherited a mess of a project that uses whatever casing the previous programmer felt like using at the moment (seriously! all caps, lowercase, pascal-casing & camel-casing - take your pick!), so I can't use the trick of putting this in the WebApiConfig.cs file because it will break the existing API calls:
// Enforce camel-casing for the JSON objects being returned from API calls.
config.Formatters.OfType<JsonMediaTypeFormatter>().First().SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
So I'm using a custom class that uses the JSON.Net serializer. Here is the code:
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class JsonNetApiController : ApiController
{
public string SerializeToJson(object objectToSerialize)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
};
if (objectToSerialize != null)
{
return JsonConvert.SerializeObject(objectToSerialize, Formatting.None, settings);
}
return string.Empty;
}
}
The problem is that the raw data returned looks like this:
"[{\"average\":54,\"group\":\"P\",\"id\":1,\"name\":\"Accounting\"}]"
As you can see, the backslashes mess things up. Here is how I'm calling using the custom class:
public class Test
{
public double Average { get; set; }
public string Group { get; set; }
public int Id { get; set; }
public string Name { get; set; }
}
public class SomeController : JsonNetApiController
{
public HttpResponseMessage Get()
var responseMessage = new List<Test>
{
new Test
{
Id = 1,
Name = "Accounting",
Average = 54,
Group = "P",
}
};
return Request.CreateResponse(HttpStatusCode.OK, SerializeToJson(responseMessage), JsonMediaTypeFormatter.DefaultMediaType);
}
What can I do differently to get rid of the backslashes? Is there an alternative way to enforcing camel-casing?
Thanks to all the references to other Stackoverflow pages, I'm going to post three solutions so anyone else having a similar issue can take their pick of the code. The first code example is one that I created after looking at what other people were doing. The last two are from other Stackoverflow users. I hope this helps someone else!
// Solution #1 - This is my solution. It updates the JsonMediaTypeFormatter whenever a response is sent to the API call.
// If you ever need to keep the controller methods untouched, this could be a solution for you.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiController : ApiController
{
public HttpResponseMessage CreateResponse(object responseMessageContent)
{
try
{
var httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, responseMessageContent, JsonMediaTypeFormatter.DefaultMediaType);
var objectContent = httpResponseMessage.Content as ObjectContent;
if (objectContent != null)
{
var jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
httpResponseMessage.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, jsonMediaTypeFormatter);
}
return httpResponseMessage;
}
catch (Exception exception)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, exception.Message);
}
}
}
The second solution uses an attribute to decorate the API controller method.
// http://stackoverflow.com/questions/14528779/use-camel-case-serialization-only-for-specific-actions
// This code allows the controller method to be decorated to use camel-casing. If you can modify the controller methods, use this approach.
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http.Filters;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiMethodAttribute : ActionFilterAttribute
{
private static JsonMediaTypeFormatter _camelCasingFormatter = new JsonMediaTypeFormatter();
static CamelCasedApiMethodAttribute()
{
_camelCasingFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public override void OnActionExecuted(HttpActionExecutedContext httpActionExecutedContext)
{
var objectContent = httpActionExecutedContext.Response.Content as ObjectContent;
if (objectContent != null)
{
if (objectContent.Formatter is JsonMediaTypeFormatter)
{
httpActionExecutedContext.Response.Content = new ObjectContent(objectContent.ObjectType, objectContent.Value, _camelCasingFormatter);
}
}
}
}
// Here is an example of how to use it.
[CamelCasedApiMethod]
public HttpResponseMessage Get()
{
...
}
The last solution uses an attribute to decorate the entire API controller.
// http://stackoverflow.com/questions/19956838/force-camalcase-on-asp-net-webapi-per-controller
// This code allows the entire controller to be decorated to use camel-casing. If you can modify the entire controller, use this approach.
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http.Controllers;
using Newtonsoft.Json.Serialization;
public class CamelCasedApiControllerAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings httpControllerSettings, HttpControllerDescriptor httpControllerDescriptor)
{
var jsonMediaTypeFormatter = httpControllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
httpControllerSettings.Formatters.Remove(jsonMediaTypeFormatter);
jsonMediaTypeFormatter = new JsonMediaTypeFormatter
{
SerializerSettings =
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}
};
httpControllerSettings.Formatters.Add(jsonMediaTypeFormatter);
}
}
// Here is an example of how to use it.
[CamelCasedApiController]
public class SomeController : ApiController
{
...
}
If you want to set it globally you can just remove the current Json formatter from the HttpConfiguration and replace it with your own.
public static void Register(HttpConfiguration config)
{
config.Formatters.Remove(config.Formatters.JsonFormatter);
var serializer = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
var formatter = new JsonMediaTypeFormatter { Indent = true, SerializerSettings = serializer };
config.Formatters.Add(formatter);
}
Comment on https://stackoverflow.com/a/26506573/887092 works for some cases but not others
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
This way works in other cases
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
So, cover all bases with:
private void ConfigureWebApi(HttpConfiguration config)
{
//..
foreach (var jsonFormatter in config.Formatters.OfType<JsonMediaTypeFormatter>())
{
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
var singlejsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
singlejsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
I am using Breeze WebAPI to save a new row to my database but when I try to call the method SaveChanges() I get the error Invalid object name 'dbo.tblAgencyQuery.
See below for my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Breeze.WebApi;
using AgencyUpdate.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AgencyUpdate.Controllers
{
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<AgencyDbContext> _ContextProvider =
new EFContextProvider<AgencyDbContext>();
[HttpGet]
public string MetaData()
{
return _ContextProvider.Metadata();
}
[HttpGet]
public IQueryable<api_Agency> GetAgency()
{
return _ContextProvider.Context.api_Agency;
}
[HttpPost]
public void SaveData(JObject data)
{
Newtonsoft.Json.Linq.JToken[] agency = data.GetValue("agency").ToArray();
dynamic DeserializedData = JsonConvert.DeserializeObject(agency[0].ToString());
//using (var context = new AgencyDbContext())
//{
// tblAgencyQuery AgencyQuery = new tblAgencyQuery(); {
// AgencyQuery.QueryID = Guid.NewGuid();
// AgencyQuery.QueryText = agency[0].ToString();
// AgencyQuery.AgencyID = DeserializedData.agencyID;
// };
// context.tblAgencyQuery.Add(AgencyQuery);
// context.SaveChanges();
//}
tblAgencyQuery tblAgencyQuery = new tblAgencyQuery();
tblAgencyQuery.QueryID = Guid.NewGuid();
tblAgencyQuery.QueryText = agency[0].ToString();
tblAgencyQuery.AgencyID = DeserializedData.agencyID;
_ContextProvider.Context.tblAgencyQuery.Add(tblAgencyQuery);
_ContextProvider.Context.Entry(tblAgencyQuery).State = System.Data.EntityState.Added;
_ContextProvider.Context.SaveChanges();
}
[HttpGet]
public IQueryable<api_AgencyOffice> GetOffice()
{
return _ContextProvider.Context.api_AgencyOffice;
}
[HttpGet]
public IQueryable<api_AgencyContact> GetContact()
{
return _ContextProvider.Context.api_AgencyContact;
}
}
}
I am calling public void SaveData(JObject data) from my javascript. I deserialize the data and assign the values to a new instance of tblAgencyQuery. Then I add it to the context so I have the data ready to be saved.
But SavedChanges() doesn't like my object. Is it expecting a different object?
This is the exception window
My JavaScript Method
var saveChanges = function (agencyObservable) {
if (agencyObservable) {
var data = ko.toJSON(agencyObservable);
var options = {
url: '/breeze/SaveData',
type: 'POST',
dataType: 'json',
data: data,
contentType: "application/json; charset=utf-8"
}
return $.ajax(options)
.then(saveSucceeded)
.fail(saveFailed);
function saveSucceeded(saveResult) {
log('Saved data successfully', saveResult, true);
};
function saveFailed(error) {
var msg = 'Save failed: ' + error.message;
logger.log(msg, error, system.getModuleId(datacontext), true);
error.message = msg;
}
}
};
You should be calling Breeze's EntityManager.saveChanges method. This will connect to a server side SaveChanges method that in turn makes use of Breeze's ContextProvider.SaveChanges method. In your code snippet, you are basically bypassing Breeze's entire save mechanism. The Breeze zip available on the Breeze web site contains a number of samples that show how this should be done.
On the client:
myEntityManager.saveChanges().then(saveSucceeded).fail(saveFailed);
On the server
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return ContextProvider.SaveChanges(saveBundle);
}