Object is null when passed to web api in c# - asp.net-mvc

I have created web api in asp.net mvc. What I want is to call that post method in web api from another project (website) in asp.net.
Here is my Class Vendor
[ModelBinder(typeof(VendorModelBinder))]
public class Vendor
{
public string VenName { get; set; }
public string VenCompany { get; set; }
}
Here is VendorModelBinder
public class VendorModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(Vendor))
{
return false;
}
Vendor result = JsonConvert.DeserializeObject<Vendor>
(actionContext.Request.Content.ReadAsStringAsync().Result);
bindingContext.Model = result;
return true;
}
Here is my VendorController
public class VendorController : ApiController
{
// POST: api/Vendor/5
[HttpPost]
[Route("")]
public HttpResponseMessage Post([ModelBinder]Vendor Ven)
{
SqlConnection con = new SqlConnection(" Data Source = DELL; Initial Catalog = EVENT; Integrated Security = True");
SqlCommand com = new SqlCommand("[dbo].[InsVendor]", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#user", Ven.VenName);
com.Parameters.AddWithValue("#compnay", Ven.VenCompany);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
HttpResponseMessage message = Request.CreateResponse(HttpStatusCode.OK);
message.Content = content;
return message;
}
}
Here I am calling the post method in web api
static async Task<Uri> AddVendorAsync(AllVendor Ven)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56908/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(JsonConvert.SerializeObject(Ven), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("api/Vendor", content);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
// return URI of the created resource.
return response.Headers.Location;
}
}
Is the above procedure correct?
Because I am getting the null object at the Vendor Controller (Ven.VenName)
Kindly, help me on this one.
Thanks.

Related

Call Webapi with Dictionary<String, object> as parameter from ASP .NET MVC Application

I have a WebApi defined as below
public ActionResult DoSomeAction([FromForm(Name = "file")] IFormFile dataFile,
Dictionary<string,object> collection)
{
//do something
}
I am trying to call this from my client as shown below,
using (var client = new HttpClient())
{
var api_Uri = Environment.GetEnvironmentVariable("API_URL");
client.BaseAddress = new Uri(api_Uri);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("a", "sasas");
data.Add("b", "sasas");
data.Add("", "sasas");
var inputSerialized = JsonSerializer.Serialize(data);
var stringContent = new StringContent(inputSerialized , Encoding.UTF8, "application/json");
var requestString = string.Format("api/DoSomeAction?selectedRule={0}", stringContent);
HttpResponseMessage Res = await client.PostAsync(requestString, multipartContent);
}
multipartContent is MultipartFormDataContent which contains File information.
The above code is not working. Some guidance would be appreciated.
I was able to solve this my implementing a custom IModelBinder.
I moved IFormFile and Dictionary to a class.
While creating the request as below ,
internal MultipartFormDataContent GetRequestParams(IFormFile FilePath)
{
MultipartFormDataContent multipartContent = GetFileContent(FilePath);
var dataExtractor = new DataExtractor();
var dictionaryData = dataExtractor.GetDictionary(); //This return Dictionary<string,object>
var serialisedData = JsonSerializer.Serialize(dictionaryData);
var stringContent = new StringContent(serialisedData, Encoding.UTF8, "application/json");
multipartContent.Add(stringContent, "MyCollection");
return multipartContent;
}
private MultipartFormDataContent GetFileContent(IFormFile FilePath)
{
byte[] data;
using (var br = new BinaryReader(FilePath.OpenReadStream()))
{
data = br.ReadBytes((int) FilePath.OpenReadStream().Length);
}
ByteArrayContent bytes = new ByteArrayContent(data);
MultipartFormDataContent multiContent = new MultipartFormDataContent();
multiContent.Add(bytes, "File", FilePath.FileName);
//Key is "File", bcos my property name in class is File. This should match
return multiContent;
}
Custom class containing the data
public class Input
{
public IFormFile File { get; set; }
[ModelBinder(BinderType = typeof(FormDataJsonBinder))]
public Dictionary<string,object> MyCollection{ get; set; }
}
Custom IModelBinder implementation
public class FormDataJsonBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
try
{
var result = JsonSerializer.Deserialize(value, bindingContext.ModelType);
bindingContext.Result = ModelBindingResult.Success(result);
}
catch (Exception ex)
{
bindingContext.Result = ModelBindingResult.Failed();
}
return Task.CompletedTask;
}
}
}
Web Api Signature
public IActionResult ExecuteRule([FromForm] Input inputdata)
{
// Do something
}

GetExternalLoginInfoAsync returns null MVC

I receive the following code error when trying to run my MVC application from localhost using Microsoft AD. When debugging the application I noticed that GetExternalLoginInfoAsync returns null. However, the application runs fine on the web. What am I missing? Somebody please help. I have posted my code below the error message.
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 140: {
Line 141: ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
Line 142: ClaimsIdentity claimsIdentity = loginInfo.ExternalIdentity;
Line 143: ApplicationUser applicationUser = new ApplicationUser(claimsIdentity);
Line 144: IdentityResult result = await UserManager.PersistAsync(applicationUser);
My code:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using SampleQuoteTracker.Models;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SampleQuoteTracker.Controllers
{
/// <summary>
/// Provides methods for accepting and desplaying account authenication and creating new accounts.
/// </summary>
public class AccountController : Controller
{
//
// GET: /Account/Login
public ActionResult Login(string returnUrl)
{
ViewBag.Title = "Log In";
LoginViewModel loginViewModel = new LoginViewModel()
{
ReturnUrl = returnUrl
};
return View(loginViewModel);
}
//
// POST: /Account/Login
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<JsonResult> Login(LoginViewModel model)
{
// seed return object optimistically
AjaxResultModel loginResult = new AjaxResultModel
{
Status = "Valid",
ReturnUrl = GetLocalUrl(model.ReturnUrl),
Message = null
};
if (Request.IsAjaxRequest())
{
if (!ModelState.IsValid)
{
loginResult.Status = "Invalid";
loginResult.Message = Tools.ListModelStateErrors(ModelState);
}
if (loginResult.Status == "Valid")
{
SignInStatus result = await SignInManager.PasswordSignInAsync(
model.Email,
model.Password,
model.RememberMe,
shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
loginResult.Status = "Success";
break;
case SignInStatus.LockedOut:
loginResult.Status = "LockOut";
loginResult.Message = AlertMessages.AccountLockOut;
break;
case SignInStatus.Failure:
default:
loginResult.Status = "Failure";
loginResult.Message = AlertMessages.AuthenticationFailure;
break;
}
}
}
return Json(loginResult);
}
//
// POST: /Account/LogOff
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
//AuthenticationManager.SignOut();
//return RedirectToAction("SignOutCallback");
return null;
}
public void SignIn(string returnUrl = "/")
{
if (returnUrl == "/")
{
returnUrl = Request.ApplicationPath;
}
Uri baseUri = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port).Uri;
Uri uri = new Uri(baseUri, returnUrl);
// If this action is called and the user is already authenticated,
// it means the user is not a member of the appropriate role for
// the controller/action requested.
if (Request.IsAuthenticated)
{
RouteValueDictionary values = RouteDataContext.RouteValuesFromUri(uri);
string controllerName = (string)values["controller"];
string actionName = (string)values["action"];
string errorUrl = Url.Action("Error",
routeValues: new
{
message = "You are not authorized to view this content",
controllerName,
actionName
});
Response.Redirect(errorUrl, true);
}
else
{
// https://stackoverflow.com/a/21234614
// Activate the session before login to generate the authentication cookie correctly.
Session["Workaround"] = 0;
// Send an OpenID Connect sign-in request.
string externalLoginCallback = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
AuthenticationManager.Challenge(new AuthenticationProperties { RedirectUri = externalLoginCallback },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
//public IAuthenticationManager AuthenticationManager
//{
// get { return HttpContext.GetOwinContext().Authentication; }
//}
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
ExternalLoginInfo loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
ClaimsIdentity claimsIdentity = loginInfo.ExternalIdentity;
ApplicationUser applicationUser = new ApplicationUser(claimsIdentity);
IdentityResult result = await UserManager.PersistAsync(applicationUser);
if (result.Succeeded)
{
claimsIdentity = await applicationUser.GenerateUserIdentityAsync(UserManager);
}
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, claimsIdentity);
return Redirect(returnUrl);
}
[Authorize]
public void SignOut()
{
string callbackUrl = Url.Action("SignOutCallback", "Account", null, Request.Url.Scheme);
AuthenticationProperties properties = new AuthenticationProperties { RedirectUri = callbackUrl };
AuthenticationManager.SignOut(
properties,
OpenIdConnectAuthenticationDefaults.AuthenticationType,
CookieAuthenticationDefaults.AuthenticationType,
Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
}
public ActionResult Error(string message, string controllerName = "Account", string actionName = "SignIn")
{
Exception exception = new Exception(message);
HandleErrorInfo handleErrorInfo = new HandleErrorInfo(exception, controllerName, actionName);
return View("Error", handleErrorInfo);
}
public ActionResult SignOutCallback()
{
if (Request.IsAuthenticated)
{
// Redirect to home page if the user is authenticated.
return RedirectToAction("Index", "Home");
}
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing && UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
base.Dispose(disposing);
}
#region Helpers
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
private IAuthenticationManager _authenticationManager;
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
/// <summary>
/// Gets a reference to the <see cref="ApplicationSignInManager"/>.
/// </summary>
protected ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set { _signInManager = value; }
}
protected ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
protected IAuthenticationManager AuthenticationManager
{
get
{
return _authenticationManager ?? HttpContext.GetOwinContext().Authentication;
}
private set
{
_authenticationManager = value;
}
}
/// <summary>
/// Ensures the <paramref name="returnUrl"/> belongs to this application.
/// <para>We don't want to redirect to a foreign page after authentication.</para>
/// </summary>
/// <param name="returnUrl">a <see cref="System.String"/> containing the page address that required authorization.</param>
/// <returns>a <see cref="System.String"/> containing a local page address.</returns>
private string GetLocalUrl(string returnUrl)
{
if (!Url.IsLocalUrl(returnUrl))
{
return Url.Action("Index", "Home");
}
return returnUrl;
}
private class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
private class RouteDataContext : HttpContextBase
{
public override HttpRequestBase Request { get; }
private RouteDataContext(Uri uri)
{
string url = uri.GetLeftPart(UriPartial.Path);
string qs = uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
Request = new HttpRequestWrapper(new HttpRequest(null, url, qs));
}
public static RouteValueDictionary RouteValuesFromUri(Uri uri)
{
return RouteTable.Routes.GetRouteData(new RouteDataContext(uri)).Values;
}
}
#endregion
}
}
Eventually the ExternalCookie is removed when the Owin middleware inspects the context.
That way AuthenticationManager.GetExternalLoginInfo() returns null after logging in, the cookie holding the info has been removed and replaced by a ApplicationCookie.
So add the following in your Startup.cs
public void ConfigureAuth(IAppBuilder app)
{
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/LogOn")
});
....
}
For more details, you could refer to this article.

Call WCF Restful POST Method in MVC 5

I have to create simple WCF web service with GET and POST. See bellow source code
public interface ISample
{
[OperationContract]
[WebGet(UriTemplate = "/GetDEPT", RequestFormat = WebMessageFormat.Json,ResponseFormat = WebMessageFormat.Json)]
Task<IEnumerable<DEPT>> GetDEPT();
[OperationContract]
[WebInvoke(UriTemplate = "UpdateDEPT?Id={Id}&StatusId={StatusId}", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Task<bool> UpdateDEPT(List<DEPT> DEPT, string Id, string StatusId);
}
ISample interface Implementation : Sample
public class Sample: ISample
{
public async Task<IEnumerable<DEPTt>> GetDEPT()
{
return await DEPTBO.GetDEPT();
}
public async Task<bool> UpdateDEPT(List<DEPTt> DEPT, string Id, string StatusId)
{
return await DEPTBO.UpdateDEPTAsync(Id, DEPT, StatusId);
}
}
How to call this WCF Restful service in MVC 5?
Please help me Service integration in MVC Application
Now i found the solution for my question.
I have create class for proxy
namespace WCF.WCFService
{
public static class WebService<T> where T : class
{
public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
public static IEnumerable<T> GetDataFromService(string Method, string param = "")
{
var client = new WebClient();
var data = client.DownloadData(appSettings + Method + param);
var stream = new System.IO.MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(IEnumerable<T>));
var result = obj.ReadObject(stream);
IEnumerable<T> Ts = (IEnumerable<T>)result;
return Ts;
}
}
public static class WebServiceUpdate
{
public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];
public static bool GetDataFromService_Update(string Method, List<CNHDataModel.CustomEntities.Port> portData, string param = "")
{
bool _res = false;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<CNHDataModel.CustomEntities.Port>));
MemoryStream mem = new MemoryStream();
serializer.WriteObject(mem, portData);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString(appSettings + Method + param, "POST", data);
_res = true;
bool Ts = (bool)_res;
return Ts;
}
}
}
Bellow, call the service proxy from controller
public class DEPTController : Controller
{
[ActionName("DEPTView")]
public ActionResult DEPTViewAsync()
{
try
{
IEnumerable<DEPT> DEPT = CNHService.WebService<DEPT>.GetDataFromService("GetDEPT");
if (port == null)
{
return HttpNotFound();
}
IEnumerable<Status> Status = CNHService.WebService<Status>.GetDataFromService("GetStatusAsync");
if (port == null || Status == null)
{
return HttpNotFound();
}
}
catch (Exception ex)
{
}
return View();
}
[HttpPost]
[ActionName("DEPTView")]
public ActionResult DEPTViewAsync([Bind(Include = "id,Statusid")] DEPT DEPTMENT)
{
try
{
List<DEPT> objDEPT = Session["DEPTItems"] as List<DEPT>;
List<DEPTStatus> objStatus = Session["DEPTIStatus"] as List<PortStatus>;
ViewBag.DEPTList = new SelectList(objDEPTt, "id", "Name");
ViewBag.DEPTStatusList = new SelectList(objStatus, "id", "Name");
if (ModelState.IsValid)
{
WebServiceUpdate.GetDataFromService_Update("UpdateDEPT", objDEPT, "?Id=" + DEPTMENT.Id + "&StatusId=" + DEPTMENT.Statusid);
setting.Message = true;
}
else
{
return View(setting);
}
}
catch (Exception ex)
{
}
return View(setting);
}
}
I hope this code help to WCF Restful service integration in MVC 5

Unable to retrieve UserData on Forms authentication ticket

I am trying to get some custom field values from my authentication ticket by running the following code in my controller -
[HttpPost]
public ActionResult Add(AddCustomerModel customer)
{
customer.DateCreated = DateTime.Now;
customer.CreatedBy = ((CustomPrincipal)(HttpContext.User)).Id;
customer.LastUpdated = DateTime.Now;
customer.LastUpdateBy = ((CustomPrincipal)(HttpContext.User)).Id;
if (ModelState.IsValid)
{
_customerService.AddCustomer(customer);
return RedirectToAction("Index");
}
return View(customer);
}
When I try and set the CreatedBy field for the new customer, I get the following error -
Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'GMS.Core.Models.CustomPrincipal'.
My userData field within the FormsAuthenticationTicket is set with a JSON string which contains two fields - Id and FullName.
Here is my login method on the controller -
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (Membership.ValidateUser(model.EmailAddress, model.Password))
{
LoginModel user = _userService.GetUserByEmail(model.EmailAddress);
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.Id = user.ID;
serializeModel.FullName = user.EmailAddress;
//serializeModel.MergedRights = user.MergedRights;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
user.EmailAddress,
DateTime.Now,
DateTime.Now.AddHours(12),
false,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
return RedirectToAction("Index", "Dashboard");
}
return RedirectToAction("Index");
}
Any ideas where I am going wrong?
To retrieve the userdata from cookies you can use the following code
FormsIdentity formsIdentity = HttpContext.Current.User.Identity as FormsIdentity;
FormsAuthenticationTicket ticket = formsIdentity.Ticket;
string userData = ticket.UserData;
You need to create and AuthenticationFilter to change your GenericPrincipal to your CustomPrincipal
public class FormAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
private readonly IResolver<HttpContextWrapper> httpContextWrapper;
private readonly IResolver<ISecurityProvider> securityProviderResolver;
public FormAuthenticationFilter(IResolver<HttpContextWrapper> httpContextWrapper, IResolver<ISecurityProvider> securityProviderResolver)
{
this.httpContextWrapper = httpContextWrapper;
this.securityProviderResolver = securityProviderResolver;
}
public void OnAuthentication(AuthenticationContext filterContext)
{
if (filterContext.Principal != null && !filterContext.IsChildAction)
{
if (filterContext.Principal.Identity.IsAuthenticated &&
filterContext.Principal.Identity.AuthenticationType.Equals("Forms", StringComparison.InvariantCultureIgnoreCase))
{
// Replace form authenticate identity
var formIdentity = filterContext.Principal.Identity as FormsIdentity;
if (formIdentity != null)
{
var securityProvider = this.securityProviderResolver.Resolve();
var principal = securityProvider.GetPrincipal(filterContext.Principal.Identity.Name, formIdentity.Ticket.UserData);
if (principal != null)
{
filterContext.Principal = principal;
this.httpContextWrapper.Resolve().User = principal;
}
}
}
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
}
}
And then register that filter to GlobalFilter
GlobalFilters.Filters.Add(new FormAuthenticationFilter());
The HttpContextWrapper in my code is just the wrapper of HttpContext.Current. You can change it to whatever you need. And the IAuthenticationFilter only exist in MVC 5.

web api call from code behind

i am very new to mvc web api
I have crated a web api Post method which takes an object type "Bag" and return a HTMLString the code is as shown bellow
public HtmlString PostBag(Bag bagofItem)
{
return Utility.PostBagDiscountedItem(bagofItem);
}
now from my web site i wanted to call the API method PostBag from the controller PostBag()
and i am do not know how to and appreciate if some one can show me how to do this
what i have got in my web application is as bellow.
public class HomeController : Controller
{
private Bag _bag = new Bag();
private string uri = "http://localhost:54460/";
public ActionResult PostBag()
{
// would some one show me how to POST the _bag to API Method PostBag()
return View();
}
public class Bag
{
private static List<Product> _bag { get; set; }
public List<Product> GetBag ()
{
if (_bag == null)
_bag = new List<Product>();
return _bag;
}
}
Try this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:54460/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(_bag);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Error with feed");
}
}

Resources